package echo.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;

@Sharable                                       //1
public class EchoServerHandler extends
        ChannelHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx,
        Object msg)  throws Exception{
//        ByteBuf in = (ByteBuf) msg;
//		System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8)); // 2
//		// ctx.write(in);

		ByteBuf buf = (ByteBuf)msg;
        byte[]req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        System.out.println("Server received: " + new String(req,"UTF-8")); // 2
        String body = " now is -- " + new String(req,"UTF-8") + " -www ";
        
		final ByteBuf firstMessage;
		req = (body).getBytes();
		firstMessage = Unpooled.buffer(req.length);
		firstMessage.writeBytes(req);// 3
		ctx.write(firstMessage);
	}

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)//4
        .addListener(ChannelFutureListener.CLOSE);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
        Throwable cause) {
        cause.printStackTrace();                //5
        ctx.close();                            //6
    }
}